import Api from "@/api/api-declare";
import type { ApiWalletTypes } from "@/api/api-types/api-wallet-types";
import PD from "../libs";

/**
 * 钱包公共服务
 */
export function useWalletCommon () {
	//获取钱包相关的短信验证码
	const getWalletSmsCode = () => {
		return new Promise((r) => {
			Api.ApiWallet.getSmsCode().then(r);
		});
	};
	return {
		getWalletSmsCode
	};
};


export function useBankCard() {
	const bankCardList = ref<ApiWalletTypes.BankCardItem[]>([]);//银行卡列表

	//获取银行卡列表
	const getBankCards = (): Promise<void> => {
		return new Promise((r) => {
			Api.ApiWallet.getBankCardList().then(res => {
				res.items && (bankCardList.value = res.items);
				r();
			});
		});
	};

	//银行列表
	const bankOps = ref<ApiWalletTypes.BankOpsItem[]>([]);

	//获取银行列表
	const getBankOps = () : Promise<void> => {
		return new Promise((r) => {
			if (bankOps.value.length) {
				r();
			};
			Api.ApiWallet.getBankList().then(res => {
				res.items && (bankOps.value = res.items);
				r();
			});
		});
	};


	//设置默认银行卡
	const setBankCard2Default = (card_id : number) : Promise<void> => {
		return new Promise((r,j) => {
			Api.ApiWallet.setDefaultBankCard({
				card_id,
			}).then(r).catch(j);
		});
	};

	return {
		bankCardList,
		/**
		 * 获取银行卡列表
		 */
		getBankCards,

		bankOps,
		/**
		 * 获取银行列表
		 */
		getBankOps,
		/**
		 * 设置默认银行卡
		 */
		setBankCard2Default
	};
};

//钱包信息
export function useWalletData () {
	//钱包金额统计
	const stat = ref({
		sum_amount : 0,
		wait_settlement_amount : 0,//待结算金额
		flow_amount : 0
	});

	//钱包记录列表
	const walletDataList = ref<ApiWalletTypes.WalletRecordItem[]>([]);

	//请求入参
	const walletDataQuery = ref<ApiWalletTypes.GetWalletDataReq>({
		type : '',
		page : 1,
		page_size : 20,
		channel : 0
	});

	//列表请求接口
	const getWalletData = () : Promise<void> => {
		return new Promise((r) => {
			PD.UniHelp.loading();
			Api.ApiWallet.getWalletData(walletDataQuery.value).then(res => {
				(res.stat) && (stat.value = res.stat);
				(res.items) && (walletDataList.value = [...walletDataList.value, ...res.items]);
				r();
			}).finally(() => PD.UniHelp.loading(false));
		});
	};

	const walletAmountData = ref({
		amount : 0,//钱包可提现余额
		is_withdraw : false,//当日是否可提现
	});

	//获取钱包可提现余额与状态
	const getWalletAmountData = () : Promise<void> => {
		return new Promise((r) => {
			Api.ApiWallet.getWalletAmountData().then(res => {
				walletAmountData.value = res;
				r();
			});
		});
	};

	return {
		stat,
		walletDataList,
		walletDataQuery,
		getWalletData,
		walletAmountData,
		getWalletAmountData
	};
}

/**
 * 司机结算规则相关
 */
export function useSettlement () {

	const settlement = ref({
		settlement_rule : 0,
		rent_deduct : 0,//租金代扣比例
	});

	const getSettlementRule = () : Promise<void> => {
		return new Promise(r => {
			Api.ApiWallet.getSettlmentRule().then(res => {
				settlement.value = res;
				r();
			});
		});
	};

	return {
		settlement,
		getSettlementRule
	};
}
